#!/usr/bin/python3
# coding: utf-8
import os, re, time
from common.read_ini import Dispose_ini

class DTB_Switching():
    def __init__(self,file,sn):
        self.ini = Dispose_ini(file)
        self.sn=sn
        self.work_dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))

    def analysis_dtb(self):
        sn = self.sn
        ini_module_name = 'compatiable'
        ini_list = self.ini.get_sections()
        if ini_module_name in ini_list:
            ini_value = self.ini.get_items(ini_module_name)
            for x,y,z in zip(ini_value[0::3],ini_value[1::3],ini_value[2::3]):
                sn_list = x[1].split('/')
                if sn in sn_list:
                    dtb_list=z[1].split('/')
                    return dtb_list[0],dtb_list[1]
            else:
                print('请检查ini文件')

    def main(self):
        dtb_name,dtb_base_name=self.analysis_dtb()
        if dtb_name != 'None' and  dtb_base_name != 'None':
            compatible = os.popen(rf"tr -d '\0' </proc/device-tree/compatible|cut -d',' -f2").read().strip()
            cmd = rf'sudo echo -n -e "\x{dtb_name}" | dd of=/dev/mmcblk0p1 bs=1 seek=0 count=1 conv=notrunc 2>/dev/null&& sudo echo -n -e "\x1" | dd of=/dev/mmcblk0p1 bs=1 seek=8192 count=1 conv=notrunc 2>/dev/null && sudo sync'
            print(cmd)
            if dtb_base_name != compatible :
                os.system(cmd)
                for i in range(1,5):
                    print(f"Switch branches, prepare to restart, countdown{6-i}")
                    time.sleep(1)
                return 1
            else:
                print("Currently the best DTB branch")
                return 0
        else:
            print("跳过dtb检测")
            return 0


if __name__ == '__main__':
    work_dir_path = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    d = DTB_Switching(f'{work_dir_path}/config.ini',"LC11286404")
    print(d.main())